/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.meego.common.gearman;

import com.meego.common.config.Config;
import com.meego.common.log.GA;
import java.util.ArrayList;
import java.util.List;
import org.gearman.worker.GearmanFunction;

/**
 *
 * @author TueHM
 */
public class GearmanManager {

    public void start(String[] args) {
        String serviceName = args[0];

        List functions = new ArrayList();
        if (args.length == 0) {
            return;
        }
        try {
            String host = Config.getStrConfig(serviceName + "host", "");
            Integer port = Config.getIntConfig(serviceName + "port", 8800);

            int worker = Config.getIntConfig(serviceName + "worker", 2);

            String strFunction = Config.getStrConfig(serviceName + "function", "");

            String[] arrFunction = strFunction.split(":");

            for (int i = 0; i < arrFunction.length; i++) {
                if (!arrFunction[i].isEmpty()) {
                    Class c = Class.forName(arrFunction[i]);
                    if (!GearmanFunction.class.isAssignableFrom(c)) {
                        GA.service.error(arrFunction[i] + " is not an instance of " + GearmanFunction.class.getCanonicalName());

                        return;
                    }
                    functions.add(c);
                }

            }

            System.out.println("Starting service " + serviceName + " with " + worker + " worker...");
            for (int i = 0; i < worker; i++) {
                System.out.println("Starting worker " + i + "...");
                new Thread(new GearmanWorkerRunner(host, port.intValue(), functions)).start();
            }
        } catch (Exception ex) {
            GA.service.error("Having exception when start service " + serviceName, ex);
        }
    }
}